class Storage {
  constructor({ prefixKey, storage }) {
    this.storage = storage;
    this.prefixKey = prefixKey;
  }
  getKey(key) {
    return `${this.prefixKey}${key}`.toUpperCase();
  }
  set(key, value, expire) {
    //   expire默认6个小时的秒数
    const stringData = JSON.stringify({
      value,
      time: new Date(), //初始存储的时间
      expire: expire ? new Date().getTime() + expire * 1000 : null, //将expire转换为毫秒
    });

    this.storage.setItem(this.getKey(key), stringData);
  }
  get(key) {
    const result = this.getItem(key, {});
    return result ? result.value : null;
  }
  getItem(key, def = null) {
    const val = this.storage.getItem(this.getKey(key));
    if (!val) {
      return def; //查询值不存在
    }
    try {
      let { value, time, expire } = JSON.parse(val);
      //设置过期时间就校验
      if (!expire || expire > new Date().getTime()) {
        return { value, time };
      }
      this.remove(key);
      return def;
    } catch (error) {
      //过期就删除key
      this.remove(key);
      return def;
    }
  }
  remove(key) {
    this.storage.removeItem(this.getKey(key));
  }
  clear() {
    this.storage.clear();
  }
}

/**
 * 创建本地存储对象，默认使用sessiongStorage
 * @param {*} param0
 * @returns
 */
export function createStorage({ prefixKey = "", storage = sessionStorage }) {
  return new Storage({ prefixKey, storage });
}
